<template>
  <f7-page no-toolbar no-navbar no-swipeback login-screen>
    <f7-login-screen-title>脱贫攻坚督查</f7-login-screen-title>
    <f7-list form>
      <f7-list-item>
        <f7-label>用户名</f7-label>
        <f7-input type="text" error-message="请输入用户名" validate required :autofocus="namefocus" clear-button :error-message-force="show_username_error" v-model="username" @input="username = $event.target.value"></f7-input>
      </f7-list-item>
      <f7-list-item>
        <f7-label>密码</f7-label>
        <f7-input type="password" error-message="请输入密码" validate required :autofocus="pwdfocus" clear-button :error-message-force="show_password_error" @input="password = $event.target.value"></f7-input>
      </f7-list-item>
    </f7-list>
    <f7-list>
      <f7-button fill round @click="signIn" style="width: 80%; margin: 0 auto;">登 &nbsp; 录</f7-button>
      <f7-block-footer>永顺县脱贫攻坚督查系统</f7-block-footer>
    </f7-list>
  </f7-page>
</template>
<script>
import { f7Page, f7LoginScreenTitle, f7List, f7ListItem, f7Label, f7Input, f7Button, f7BlockFooter } from 'framework7-vue'
import Vue from 'vue'
import md5 from "blueimp-md5"
import { mapActions } from 'vuex'
export default {
  components: {
    f7Page,
    f7LoginScreenTitle,
    f7List,
    f7ListItem,
    f7Label,
    f7Input,
    f7Button,
    f7BlockFooter
  },
  data() {
    return {
      username: localStorage.username || '',
      password: '',
      show_username_error: false,
      show_password_error: false,
      namefocus: !localStorage.username,
      pwdfocus: !!localStorage.username
    }
  },
  methods: {
    ...mapActions([
      'update_user'
    ]),
    async signIn() {
      this.show_username_error = !this.username
      this.show_password_error = !this.password
      if (!this.username || !this.password) return
      const login = await this.request('/login', { username: this.username, password: md5(`${this.password}tpgj`) })
      if (login.code === 0) {
        this.$f7.toast.show({ text: login.msg })
      } else if (login.code === 1) {
        localStorage.username = this.username
        this.update_user(login.data)
        
        // 获取字典数据
        let ids = []
        login.data.place.filter(item => item.level === 1).forEach(item => {
          ids.push(item.id)
        })

        const place = await this.request('/getplace', { ids: ids.join(',') })
        if (place.code === 1) {
          localStorage.place = JSON.stringify(place.data)
          Vue.prototype.place = place.data
        }

        this.$f7router.navigate('/index', { reloadAll: true })
      }
    }
  }
}
</script>